package cn.calm.j2se.jpa.util;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.zip.ZipException;

import cn.calm.j2se.jpa.entity.Bundle;
import cn.calm.j2se.jpa.entity.BundleInfo;
import cn.calm.j2se.jpa.entity.BundleInfoPK;
import cn.calm.j2se.jpa.entity.BundlePK;


public class BundleUtil {
	public static Bundle readBundleInfo(String filePath) {
		Bundle bundle=null;
		try {
			JarFile file = new JarFile(filePath);
			Manifest manifest = file.getManifest();
			Attributes attributes = manifest.getMainAttributes();
			String symbolicName = attributes.getValue("Bundle-SymbolicName");
			if (symbolicName == null) {
				throw new Exception("该文件不是个Bundle");
			}
			String bundleVersion = attributes.getValue("Bundle-Version");
			if (bundleVersion == null) {
				throw new Exception("该文件不是个Bundle");
			}
			bundle = new Bundle();
			BundlePK key = new BundlePK();
			key.setBundleSymbolicName(symbolicName);
			key.setBundleVersion(bundleVersion);
			bundle.setId(key);
			Set<Object> keys=attributes.keySet();
			Set<BundleInfo> bundleInfos=new HashSet<BundleInfo>(keys.size());
			BundleInfo info;
			BundleInfoPK infoId;
			for(Object o:keys){
				System.out.print("key:"+o);
				info=new BundleInfo();
				info.setBundle(bundle);
				infoId=new BundleInfoPK();
				infoId.setBundleVersion(bundleVersion);
				infoId.setBundleSymbolicName(symbolicName);
				infoId.setBundleInfoKey(o.toString());
				info.setId(infoId);
				System.out.println("---->value:"+attributes.get(o));
				info.setBundleInfoValue(attributes.get(o).toString());
				bundleInfos.add(info);
			}
			bundle.setBundleInfos(bundleInfos);
			
			FileInputStream fis = null;
			ByteArrayOutputStream baos = null;
			try {
				fis = new FileInputStream(filePath);
				baos = new ByteArrayOutputStream();
				int length;
				byte[] buf = new byte[1024];
				while ((length = fis.read(buf)) != -1) {
					baos.write(buf, 0, length);
				}
				bundle.setContent(baos.toByteArray());

			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (baos != null) {
					try {
						baos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (fis != null) {
					try {
						fis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		} catch (ZipException e) {
			System.out.println(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bundle;
	}
}
